/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package at.tugraz.hidipic.web.validation;

import at.tugraz.hidipic.web.bean.UserFormBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

/**
 *
 * @author mario
 */
@Component
public class UserFormBeanValidator {

    public boolean supports(Class<?> klass) {
        return UserFormBean.class.isAssignableFrom(klass);
    }

    public void validate(Object target, Errors errors, boolean edit) {
        UserFormBean ufb = (UserFormBean) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.usernameempty", "Username must not be empty.");
        String userName = ufb.getUsername();
        if (userName != null && userName.length() > 25) {
            errors.rejectValue("username", "error.usernamelength", "Username must not be longer than 25 characters");
        }
        String pw = ufb.getPassword();
        String repw = ufb.getRePassword();
        if (!edit) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "error.passwordempty", "Password must not be empty.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "rePassword", "error.retypepasswordempty", "Re-type Password must not be empty.");
        }
        if (pw != null && repw != null) {
            if (edit && StringUtils.isEmpty(pw)) {
                //do nothing
            } else {
                if (!pw.equals(repw)) {
                    errors.rejectValue("rePassword", "error.passwordsdontmatch", "Re-Type Password has to match the password.");
                }
                if (pw.length() < 4) {
                    errors.rejectValue("password", "error.passwordlength", "Password has to be longer than 4 characters.");
                }
            }
        }
    }
}
